local skynet = require "skynet"
local Http = require "core.Http"
local Json = require "lualib.Json"

local M = {}

local apiProto = skynet.getenv("api_protocol") or "http"
local apiHost = skynet.getenv("admin_host")
local adminPort = skynet.getenvn("admin_port")
if not apiHost or not adminPort then
    LERR("admin_http", "admin_ip or admin_port is nil")
    return
end

local domain = string.format("%s://%s:%d", apiProto, apiHost, adminPort)

---@param method string 请求方法, GET|POST
---@param uri string 请求地址
---@param params table|string 请求参数
---@param recvheader table|nil 响应头,如果为空表，用于响应头，如果为nil，则忽略
---@param header table|nil 请求头, nil：没有响应头
---@return number|number, table|nil    状态码和响应体
function M.request(method, uri, params, recvheader, header)
    local status, body = Http.request(method, domain, uri, params, recvheader, header)
    if status > 400 then
        return status
    end

    return status, body and json.decode(body)
end

function M.get(uri, params, recvheader, header)
    return M.request("GET", uri, params, recvheader, header)
end

function M.post(uri, params, recvheader, header)
    return M.request("POST", uri, params, recvheader, header)
end

---@param uri string 请求地址
---@param params string|table 请求参数
---@param recvheader table|nil 响应头,如果为空表，用于响应头，如果为nil，则忽略
---@param header table|nil 请求头, nil：没有响应头
---@return number|number, table|nil    状态码和响应体
function M.json(uri, params, recvheader, header)
    header["content-type"] = "application/json"
    if params then
        params = json.encode(params)
    end

    return M.request("POST", uri, params, recvheader, header)
end

return M